package ru.stepanovdn.trading.server

import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.util.ResourceUtils
import ru.stepanovdn.trading.server.repository.CandleRepository
import ru.stepanovdn.trading.server.repository.OrderRepository
import ru.stepanovdn.trading.server.service.candle.CandleHistoryService
import ru.stepanovdn.trading.server.service.dictionary.InstrumentService
import ru.stepanovdn.trading.server.service.notification.NotificationService
import ru.stepanovdn.trading.server.service.order.OrderService
import ru.stepanovdn.trading.server.service.price.PricesService
import ru.stepanovdn.trading.server.service.processor.CalculatorInstrumentByFiatService
import ru.stepanovdn.trading.server.service.processor.PurchaseService
import ru.stepanovdn.trading.server.service.report.ReportService
import ru.stepanovdn.trading.server.service.tinkoff.TinkoffMockAPI
import ru.stepanovdn.trading.server.strategy.StrategySelector
import java.time.Duration
import java.time.OffsetDateTime

@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [TestConfiguration::class])
@ActiveProfiles(profiles = ["test"])
@TestPropertySource(ResourceUtils.CLASSPATH_URL_PREFIX + "application-test.properties")
@ContextConfiguration(classes = [
    PurchaseService::class, OrderService::class, InstrumentService::class, TinkoffMockAPI::class,
    StrategySelector::class, NotificationService::class, CalculatorInstrumentByFiatService::class,
    CandleHistoryService::class, PricesService::class, ReportService::class
])
class StrategiesByCandleHistoryTests (

    @Autowired
    private var candleRepository: CandleRepository,

    @Autowired
    private var orderRepository: OrderRepository,

    @Autowired
    private var purchaseService: PurchaseService,

    @Autowired
    private var orderService: OrderService,

    @Autowired
    private var reportService: ReportService,

    @Autowired
    private  var strategySelector: StrategySelector,

    @Value("\${candle.history.duration}")
    val historyDuration: Duration? = null,

    @Value("\${tinkoff.emulator}")
    val isTinkoffEmulator: Boolean? = null
): FunSpec( {

    beforeEach {
        // удаляем существующие ордеры из БД
        orderRepository.deleteAll()
        orderService.loadOrdersFromDB()
    }

    test("checkProfitByStrategies") {
        // Проверяем свойства для тестов
        isTinkoffEmulator!! shouldBe true

        // Эмулируем поток свечей за заданный интервал (candle.history.duration)
        val days = historyDuration!!.toDays()
        val startDateTime: OffsetDateTime = OffsetDateTime.now().minusDays(days)
        strategySelector.figiesForActiveStrategies.stream()
            .flatMap { figi ->
                candleRepository.findByFigiAndIntervalAndDateTimeAfterOrderByDateTime(
                    figi,
                    "1min",
                    startDateTime
                )!!.stream()
            }
            .sorted(Comparator.comparing { it!!.dateTime })
            .forEach { c -> purchaseService.observeCandleNoThrow(c!!) }

        // Логируем отчеты
        reportService.logReportInstrumentByFiat(reportService.buildReportInstrumentByFiat())
        assert(true)
    }

})